// pages/test/test.js
const app = getApp()
const myaudio = wx.createInnerAudioContext();//语音
const di = wx.createInnerAudioContext();//语音
var listener = {};//初始化摄像头方法
var init;
var intetimes;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    millisecond1: 0,
    millisecond: 0,
    frameWidth: 0,
    frameHeight: 0,
    pixelRatio: 2,
    windowWidth: 0,
    windowHeight: 0,
    screenHeight: 100,
    utime: 0,
    index: 0,
    scan: {
      width: 0,
      height: 0,
      top: 0
    },
    isplay: false, //是否播放
    time: false, //判断是否执行createCameraContext方法
    loading:false,//判断
    state:false,//判断第一次返回值
    banben:false,//判断版本
    yfyindex:0,
    elapsedTime:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this;
    setTimeout(() => {
      that.onstart()//开始播放
      that.test()
    }, 1500)
    setTimeout(() => {
      if (this.data.banben == false) {
        wx.showToast({
          title: '手机版本过低',
          icon: 'success',
          duration: 3000,
          success: function () {
            that.allstop();
            setTimeout(function () {
              wx.switchTab({
                url: '../index/index'
              })
            }, 2000) //延迟时间 
          }
        })
      }
      // console.log('10秒了！' + this.data.time)
    }, 7000)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that=this;
    myaudio.src = app.globalData.the_host + '/image/sound/ScanSound.mp3';//初始化语音
    di.src = app.globalData.the_host + '/image/sound/5383.mp3'
    clearInterval(intetimes);//超时开始定时器
    intetimes = setInterval(function () {
      wx.showToast({
        title: '扫码超时',
        icon: 'success',
        duration: 2000,
        success: function () {
          that.allstop();
          setTimeout(function () {
            wx.switchTab({
              url: '../index/index'
            })
          }, 2000) //延迟时间 
        }
      })
    }, 20000);
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  // onHide: function () {
  //   listener.stop()
  // },
  //退出页面
  doback: function () {
    this.allstop();//停止所有
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 生命周期函数--监听页面卸载，退出页面
   */
  onUnload: function () {
    this.allstop();//停止所有
  },
  //所有的停止方法都在这里
  allstop:function(){
    this.onstop()//关闭语音
    clearInterval(intetimes);//超时定时器结束
    listener.stop();//停止取图
    this.setData({
      loading:true,
      state:true,
    });
  },
  //取图片 方法
  test:function(){
    wx.authorize({
      scope: "scope.camera"
    })
    var that = this;
    if (that.data.windowWidth == 0) {
      wx.getSystemInfo({
        success: (res) => {
          that.setData({
            windowWidth: res.windowWidth,
            windowHeight: res.windowHeight,
            pixelRatio: res.pixelRatio,
            screenHeight: res.screenHeight
          });
          console.log("获取到窗口宽高" + res.windowWidth, res.windowHeight, res.screenHeight, res.pixelRatio)
        }
      })
    }
    const context = wx.createCameraContext();
    listener = context.onCameraFrame((frame) => {
      if (this.data.frameWidth == 0) {
        var uwidth = 256 * this.data.windowWidth / frame.width;
        var uheight = 360 / 256 * uwidth;
        this.setData({
          fheight: frame.height,
          fwidth: frame.width,
          time: true,
        });
        if (frame.height < frame.width) {
          uwidth = 256 * this.data.windowWidth / frame.height;
          uheight = 360 / 256 * uwidth;
        }
        if (frame.height < frame.width) {
          if (this.data.windowWidth * this.data.pixelRatio > frame.width) {
            uwidth = this.data.windowWidth * this.data.pixelRatio / frame.height * uwidth
            uheight = this.data.windowWidth * this.data.pixelRatio / frame.height * uheight
          }
        }
        if (frame.height == 960 && frame.width == 720) {
          uwidth = uwidth * 1.45
          uheight = uheight * 1.45
        }
        var utop = this.data.screenHeight / 2 - uheight;
        var uleft = (this.data.windowWidth - uwidth) / 2
        if (frame.height == 960 && frame.width == 720) {
          utop = utop + 10
        }
        this.setData({
          frameWidth: frame.width,
          frameHeight: frame.height,
          scan: {
            width: uwidth,
            height: uheight,
            top: utop,
            left: uleft
          }
        });
      }
      // if (that.data.utime == 0) {
      //   console.log("开始取帧")
      // }
      if (that.data.loading==false) {
        that.setData({
          loading:true,
          banben:true,
          index:that.data.index+1
        });
        var nw = 256,
          nh = 360;
        //计算
        if (this.data.frameHeight < this.data.frameWidth) {
          nw = parseInt(256 / (this.data.frameHeight / this.data.frameWidth))
          nh = parseInt(360 / (this.data.frameWidth / this.data.frameHeight));
        }
        var x1 = new Uint8Array(frame.data);
        var x2 = new Uint8Array(nw * nh);
        // 计算x,y的范围
        var startx = (this.data.frameWidth - nw) / 2;
        var endx = startx + nw;
        var starty = this.data.frameHeight / 2 - nh;
        if (app.globalData.isHuaWei) {
          // starty = starty + 26 * this.data.pixelRatio
          starty = starty + 8 * this.data.pixelRatio;
        } else {
          starty = starty + 9 * this.data.pixelRatio
        }
        this.setData({
          "isHuaWei": app.globalData.isHuaWei
        });
        this.setData({
          "starty": starty
        });
        var endy = starty + nh;
        var arr = [];
        var uindex = 0;
        for (var a = 0; a < x1.length; a++) {
          var yu = (a + 1) % 4;
          if (yu != 0) {
            arr[yu - 1] = x1[a];
          } else {
            var y = parseInt(parseInt(a / 4 + 1) / this.data.frameWidth);
            var x = parseInt(parseInt(a / 4 + 1) % this.data.frameWidth);
            if (x < startx || x >= endx || y < starty || y >= endy) {
              continue;
            }
            x2[uindex] = parseInt((arr[0] * 30 + arr[1] * 59 + arr[2] * 11) / 100)
            uindex++;
          }
        }
        var s = wx.arrayBufferToBase64(x2)
        wx.request({
          url: app.globalData.the_host + '/fcode/decode',
          data: {
            "code": s,
            "width": nw,
            "isJPG": 0,
          },
          header: {
            'content-type': 'application/json'
          },
          method: "POST",
          success: function (res) {
            if (res.statusCode == 200) {
              if (that.data.state == false) {
                if (res.data.status == 0 || res.data.status == 30) {
                  that.allstop() //停止提示语音播放                  
                  that.setData({
                    loading:true,
                    state: true,
                    elapsedTime: res.data.elapsedTime,
                    yfyindex: that.data.yfyindex+1,
                    msg: res.data.message + res.data.status
                  })
                  that.onstartDi()//滴-播放
                  wx.showToast({
                    title: res.data.message,
                    icon: 'success',
                    duration: 2000
                  })
                  if (res.data.status == 30) {
                    wx.redirectTo({
                      url: '../tips/index?status=30&fcode=1&vcode=1'
                    })
                  } else {
                    wx.redirectTo({
                      url: '../tips/index?fcode=' + res.data.data.fcode + "&vcode=" + res.data.data.vcode
                    })
                  }
                } else {
                  that.setData({
                    yfyindex: that.data.yfyindex + 1,
                    elapsedTime:res.data.elapsedTime,
                    msg: res.data.message + res.data.status,
                    loading:false
                  })
                }
              }
            } else {
              that.setData({
                loading: false,
              });
              console.log("收到服务器返回" + res.statusCode)
            }
          }
        })
      }
     
     
    })
    listener.start();//执行取图方法
  },
  //开始播放音乐
  onstart: function () {
    myaudio.play();
    console.log('开始播放')
  },
  //停止播放
  onstop: function () {
    myaudio.stop();
    console.log('播放结束!')
  },
  // 开始播放音乐 滴 一下 第二个语音
  onstartDi:function(){
    di.play();
    console.log('滴-播放!')
  },
  //停止播放 滴 一下 第二个语音 
  onstopDi: function () {
    di.stop();
    console.log('滴-停止!')
  },
  //-----------------计时器--------------------
  //开始
  start: function () {
    clearInterval(init);
    var that = this;
    that.setData({
      millisecond: 0,
      millisecond1: 0
    })
    init = setInterval(function () {
      that.timer()
    }, 50);
  },
  //暂停
  stop: function () {
    clearInterval(init);
  },
  //执行时间
  timer: function () {
    var that = this;
    console.log(that.data.millisecond)
    that.setData({
      millisecond: that.data.millisecond + 50
    })
  },

})